package com.itheima.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.itheima.bean.Employee;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * 元数据对象处理器
 *  公共字段填充
 *  统一为公共字段赋值
 */
@Configuration
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private HttpSession session;

    //给那些已经标注了添加操作，填充值的字符赋值
    @Override
    public void insertFill(MetaObject metaObject) {
        System.out.println("controller..add=====" + Thread.currentThread().getId());

        Employee employee = (Employee) session.getAttribute("employee");
        System.out.println("employee ================================== " + employee);
        metaObject.setValue("createTime", LocalDateTime.now());
        metaObject.setValue("updateTime", LocalDateTime.now());
//        metaObject.setValue("createUser", employee.getId());
//        metaObject.setValue("updateUser", employee.getId());
        metaObject.setValue("createUser", BaseContext.get());
        metaObject.setValue("updateUser", BaseContext.get());
        System.out.println("BaseContext.get() ============================== " + BaseContext.get());
    }


    //给那些已经标注了更新操作，填充值的字段赋值
    @Override
    public void updateFill(MetaObject metaObject) {
        Employee employee = (Employee) session.getAttribute("employee");
        metaObject.setValue("updateTime", LocalDateTime.now());
//        metaObject.setValue("updateUser", employee.getId());

        System.out.println("BaseContext.get() ============================== " + BaseContext.get());
        metaObject.setValue("updateUser", BaseContext.get());

    }
}
